﻿using System;
using System.Collections.Generic;
using CodeFirstMVC3.Core;
using CodeFirstMVC3.DataAccess.Model;
using CodeFirstMVC3.Domain.DataAccess;
using CodeFirstMVC3.Domain.Model;
using CodeFirstMVC3.Domain.Service;

namespace CodeFirstMVC3.Service
{
    public class MemberService : IMemberService
    {
        private readonly IRepository<Member> _repository;

        public MemberService(IRepository<Member> repository)
        {
            _repository = repository;
        }

        public IMember New()
        {
            return _repository.NewEntity();
        }

        public void Add(IMember entity)
        {
            _repository.Add(entity as Member);
            _repository.Save();
        }

        public void Edit(IMember entity)
        {
            Member m = entity as Member;
            _repository.Save();
        }

        public void Remove(IMember entity)
        {
            _repository.Remove(entity as Member);
            _repository.Save();
        }

        public IMember Get(int id)
        {
            return _repository.Get(p => p.Id == id);
        }

        public IMember Get(Func<IMember, bool> predicate)
        {
            return _repository.Get(predicate);
        }

        public int GetCount(Func<IMember, bool> perdicate = null)
        {
            if (perdicate == null)
                return _repository.GetCount(p => true);
            return _repository.GetCount(perdicate);
        }

        public IEnumerable<IMember> GetAll(Func<IMember, bool> predicate = null, int start = 0, int count = ApplicationSettings.PageSize)
        {
            if (predicate == null)
                return _repository.GetAll(p => true);

            if (start == 0)
            {
                return _repository.GetAll(predicate);
            }

            return _repository.GetAll(predicate, start, count);
        }

        public IMember Authenticate(string username, string password)
        {
            var entity = _repository.Get(p => p.Username == username);

            if (entity == null)
                return null;

            var passwordHash = PasswordGenerator.GetHashPassword(password);

            if (!string.Equals(passwordHash, password))
                return null;

            return entity;
        }

        public bool Contain(string username)
        {
            return !(_repository.Get(p => p.Username == username) == null);
        }
    }
}
